<template>
  <div class="global">
    <!-- 用户顶部搜索栏 -->
    <div style="margin-bottom: 10px">
      <el-card shadow="hover">
        <el-form
          :model="room"
          label-width="70px"
          ref="ruleFormRef"
          :rules="rules"
          inline="true"
        >
          <el-form-item>
            <el-input
              v-model="room.name"
              size="large"
              placeholder="请输入会议室名称"
              :prefix-icon="Search"
              maxlength="10"
              minlength="3"
            />
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="room.location"
              size="large"
              placeholder="请输入会议室位置"
              :prefix-icon="Search"
              maxlength="11"
            />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="room.status"
              placeholder="请输入会议室状态"
              size="large"
            >
              <el-option label="预约中" value="预约中" />
              <el-option label="未预约" value="未预约" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="onSubmit" plain
              ><el-icon style="margin-right: 5px"><Search /></el-icon
              >搜索</el-button
            >
            <el-button type="primary" @click="reFresh" plain
              ><el-icon style="margin-right: 5px"><Refresh /></el-icon
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <div style="margin-bottom: 10px">
      <el-card
        shadow="hover"
        body-style="display: flex;"
      >
        <div style="margin-right: 20px">
          <el-button type="primary" @click="change" plain :disabled="isAdmin"
            ><el-icon style="margin-right: 3px"><Plus /></el-icon
            >新增</el-button
          >
        </div>
        <div style="margin-right: 20px">
          <el-button
            type="danger"
            v-if="!isAdmin"
            :disabled="batch_delete_flag"
            @click="removeUser"
            plain
            ><el-icon style="margin-right: 3px"><Delete /></el-icon
            >删除</el-button
          >
        </div>
        <div style="margin-right: 20px">
          <el-upload
            class="upload-demo"
            action="https://www.sixkey-world.top:8600/common/roomImport"
            accept=".xlsx"
            :on-success="handleExcelImportSuccess"
          >
            <el-button type="success" plain :disabled="isAdmin"
              ><el-icon style="margin-right: 3px"><Upload /></el-icon
              >导入</el-button
            >
          </el-upload>
        </div>
        <div style="margin-right: 20px">
          <el-button type="warning" @click="exportRoomData" plain :disabled="isAdmin"
            ><el-icon style="margin-right: 3px"><Download /></el-icon
            >导出</el-button
          >
        </div>
      </el-card>
    </div>

    <!-- 用户数据表格展示 -->
    <div>
      <el-table
        @selection-change="handleSelectionChange"
        :data="tableData"
        stripe
        style="width: 100%"
        height="380"
      >
        <el-table-column type="selection" width="100" />
        <el-table-column prop="name" label="会议室名" width="140" />
        <el-table-column prop="image" label="图片" width="200">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-image
                style="width: 140px; height: 90px; border-radius: 10%"
                :src="scope.row.image"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="位置" width="170" />
        <el-table-column prop="capacity" label="容量" width="120" />
        <el-table-column prop="description" label="描述" width="260" />
        <el-table-column prop="status" label="状态" width="130">
          <template #default="scope">
            <el-button
              plain
              type="success"
              size="small"
              >{{ scope.row.status }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
            <el-button
              plain
              type="primary"
              size="small"
              @click="updateUser(scope.row)"
              :disabled="isAdmin"
              ><el-icon><Edit /></el-icon>修改</el-button
            >
            <el-popconfirm
              title="确定要删除吗?"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="confirmEvent(scope.row)"
              @cancel="cancelEvent"
            >
              <template #reference>
                <el-button plain type="danger" size="small" :disabled="isAdmin"
                  ><el-icon><Delete /></el-icon>
                  删除
                </el-button></template
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>

  <!-- 用户数据搜集对话框 -->
  <el-dialog
    v-model="dialogFormVisible"
    title="新增会议室"
    :center="true"
    :align-center="true"
    width="550px"
    :show-close="false"
  >
    <el-form
      :label-position="right"
      label-width="100px"
      :model="roomForm"
      class="el_form"
      ref="ruleFormRef"
      :rules="rules"
    >
      <el-form-item label="名称" prop="name" :label-width="formLabelWidth">
        <el-input
          v-model="roomForm.name"
          size="large"
          placeholder="请输入会议室名称"
        />
      </el-form-item>
      <el-form-item label="位置" prop="location" :label-width="formLabelWidth">
        <el-input
          v-model="roomForm.location"
          size="large"
          placeholder="请输入会议室位置"
        />
      </el-form-item>
      <el-form-item label="容量" prop="capacity" :label-width="formLabelWidth">
        <el-input
          v-model="roomForm.capacity"
          :rows="3"
          size="large"
          placeholder="请输入会议室容量"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status" :label-width="formLabelWidth">
        <el-select
          v-model="roomForm.status"
          placeholder="请输入会议室状态"
          size="large"
        >
          <el-option label="预约中" value="预约中" />
          <el-option label="未预约" value="未预约" />
        </el-select>
      </el-form-item>
      <el-form-item
        label="描述"
        prop="description"
        :label-width="formLabelWidth"
      >
        <el-input
          v-model="roomForm.description"
          type="textarea"
          :rows="3"
          placeholder="描述内容，最长200字"
          maxlength="150"
        />
      </el-form-item>
      <el-form-item label="图片" prop="image">
        <el-upload
          class="avatar-uploader"
          action="https://www.sixkey-world.top:8600/common/upload"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="roomForm.image" :src="roomForm.image" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog_footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="saveRoom"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 分页部分 -->
  <div class="pagenation">
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="sizes, prev, pager, next"
      :total="total"
      prev-text="第"
      next-text="页"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>
    
  <script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  Search,
  Refresh,
  Edit,
  Delete,
  Plus,
  Download,
  Upload,
} from "@element-plus/icons-vue";
import { list, save, getRoomById, removeById, update } from "@/api/room";
import { useTokenStore } from "@/stores/token";
const TokenStore = useTokenStore();

///////////////////////////////////////////////////////////////////数据区
const tableData = ref([]);
const pageNo = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dialogFormVisible = ref(false);
const ids = ref([]);
const batch_delete_flag = ref(true);
//模糊查询数据
const room = ref({
  name: "",
  location: "",
  status: "",
});
//保存用户
const roomForm = ref({
  id: null,
  name: "",
  location: "",
  image: "",
  description: "",
  capacity: null,
  status: "",
});

///////////////////////////////////////////////////////////////////////////方法区
//异步获取用户分页数据
//检测是否是测试账号
const isAdmin = ref(false)
onMounted(async () => {
  //检测是否是测试账号
  isAdmin.value = TokenStore.isAdmin;
  const res = await list(pageNo.value, pageSize.value, room.value);
  if (res.code === 200) {
    if (res.data != null) {
      tableData.value = res.data.records;
      total.value = res.data.total;
    }
  }
});

//异步获取用户分页数据
async function initList() {
  await list(pageNo.value, pageSize.value, room.value).then((res) => {
    if (res.code === 200) {
      if (res.data != null) {
        tableData.value = res.data.records;
        total.value = res.data.total;
      }
    }
  });
}

//重置
async function reFresh() {
  if (
    room.value.name != "" ||
    room.value.location != "" ||
    room.value.status != ""
  ) {
    room.value.name = "";
    room.value.location = "";
    room.value.status = "";
    initList();
  }
}

//搜索
async function onSubmit() {
  if (
    room.value.name != "" ||
    room.value.location != "" ||
    room.value.status != ""
  ) {
    initList();
  }
}

//新增用户弹框
function change() {
  dialogFormVisible.value = !dialogFormVisible.value;
}

//获取头像路径
function handleAvatarSuccess(res) {
  roomForm.value.image = res.data;
}

//头像文件校验
function beforeAvatarUpload(file) {
  const isJPG = file.type === "image/jpeg";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    this.$message.error("上传头像图片只能是 JPG 格式!");
  }
  if (!isLt2M) {
    this.$message.error("上传头像图片大小不能超过 2MB!");
  }
  return isJPG && isLt2M;
}

//表单校验
const ruleFormRef = ref(null);
// 校验规则
const rules = {
  name: [{ required: true, message: "请输入会议室名称", trigger: "blur" }],
  location: [{ required: true, message: "请输入会议室位置", trigger: "blur" }],
  description: [
    { required: true, message: "请输入会议室描述", trigger: "blur" },
  ],
  capacity: [{ required: true, message: "请输入会议室容量", trigger: "blur" }],
  status: [{ required: true, message: "请选择会议室状态", trigger: "change" }],
  image: [{ required: true, message: "请上传会议室图片", trigger: "blur" }],
};

//新增 / 修改 用户
function saveRoom() {
  //表单校验
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      if (!roomForm.value.id) {
        //新增用户
        save(roomForm.value).then((res) => {
          if (res.code === 200) {
            ElMessage({
              showClose: true,
              message: "保存成功！",
              type: "success",
            });
            //异步请求用户分页数据
            initList();
          }
        });
      } else {
        //修改用户
        update(roomForm.value).then((res) => {
          if (res.code === 200) {
            ElMessage({
              showClose: true,
              message: "修改成功！",
              type: "success",
            });
            //异步请求用户分页数据
            initList();
          }
        });
      }
      dialogFormVisible.value = false;
      cancel();
    }
  });
}

//取消
function cancel() {
  roomForm.value.name = "";
  roomForm.value.location = "";
  roomForm.value.status = "";
  roomForm.value.capacity = 0;
  roomForm.value.description = "";
  roomForm.value.image = "";
  dialogFormVisible.value = false;
}

//修改用户：回显用户数据
function updateUser(row) {
  let text = row.status === "使用中" ? "使用中" : "预约中";

  if (row.status == "使用中" || row.status == "预约中") {
    ElMessage({
      showClose: true,
      message: "会议室处于" + text + "状态，谨慎修改！",
      type: "warning",
    });
  }
  getRoomById(row.id).then((res) => {
    if (res.code === 200) {
      roomForm.value = res.data;
      dialogFormVisible.value = true;
    }
  });
}

//批量删除用户
function removeUser() {
  //批量删除
  removeById(ids.value).then((res) => {
    if (res.code === 200) {
      ElMessage({
        showClose: true,
        message: "删除成功！",
        type: "success",
      });
      //异步请求用户分页数据
      initList();
    }
  });
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  if (ids.value.length > 0) {
    batch_delete_flag.value = false;
  }
  if (ids.value.length === 0) {
    batch_delete_flag.value = true;
  }
}

//pageSize改变时
function handleSizeChange(value) {
  pageSize.value = value;
  initList();
}

//pageNo改变时
function handleCurrentChange(value) {
  pageNo.value = value;
  initList();
}

//单个删除用户
function confirmEvent(row) {
  removeById(row.id).then((res) => {
    if (res.code === 200) {
      ElMessage({
        showClose: true,
        message: "删除成功！",
        type: "success",
      });
      //异步请求用户分页数据
      initList();
    }
  });
}

//取消删除用户
function cancelEvent() {
  ElMessage({
    showClose: true,
    message: "取消删除！",
    type: "warning",
  });
}

//用户数据导出
function exportRoomData() {
  window.open("https://www.sixkey-world.top:8600/common/roomExport");
  ElMessage({
    showClose: true,
    message: "导出成功！",
    type: "success",
  });
}

//用户数据导入
function handleExcelImportSuccess() {
  ElMessage({
    showClose: true,
    message: "导入成功！",
    type: "success",
  });
  initList();
}
</script>
  
  <style scoped>
.global {
  padding-top: 10px;
  padding-left: 10px;
  padding-right: 10px;
  background-color: #f5f5f5;
}
.pagenation {
  margin-top: 15px;
  margin-left: 500px;
}

.el-input {
  width: 260px;
}

.el_form {
  margin-top: 10px;
  margin-left: 40px;
}

.dialog_footer {
  margin-left: 260px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 0;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
    